package com.dxy.shardingjdbc.algorithm;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Description 告警表分库时间范围算法
 * @Author dangxianyue
 * @Date 2023/2/9 22:27
 */
public class AlarmSubDatabaseTimeRangeAlgorithm implements RangeShardingAlgorithm<LocalDateTime> {

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<LocalDateTime> shardingValue) {
        System.out.println("rangeSubDatabase:\navailableTargetNames: " + JSON.toJSONString(availableTargetNames) + "\nshardingValue: " + JSON.toJSONString(shardingValue));
        List<String> dbList = new ArrayList<>();
        Range<LocalDateTime> range = shardingValue.getValueRange();
        int start = range.lowerEndpoint().getYear();
        int end = range.upperEndpoint().getYear();
        for (int i = start; i <= end; i++) {
            for (String dbName : availableTargetNames) {
                if (dbName.endsWith(String.valueOf(i))) {
                    dbList.add(dbName);
                }
            }
        }
        System.out.println("range algorithm dbList: " + JSON.toJSONString(dbList));
        return dbList;
    }


}
